Page({
  data: {
    orderData: null,
    totalPrice: 0,
    discount: 20, // 优惠金额
    finalPrice: 0,
    goodsInfo: null,
    isSubmitting: false, // 是否正在提交
    currentOid: 1004, // 初始订单ID
    discountPrice: 0,
    orderInfo: null
  },

  onLoad: function(options) {
    if (options.orderData) {
      const orderData = JSON.parse(decodeURIComponent(options.orderData));
      console.log('订单确认页接收到的数据:', orderData);

      // 如果没有地址，设置默认地址
      if (!orderData.address) {
        orderData.address = '河北省保定市万博广场';
      }

      // 商品信息假数据
      const goodsInfo = {
        'KF174194004243589': {
          id: 'KF174194004243589',
          gname: '日常保洁 2小时1人急速清洁全程质保',
          price: 300,
          sales: 1000,
          prove: '/static/images/cleaning1.png'
        },
        'KF174194004243587': {
          id: 'KF174194004243587',
          gname: '深度保洁',
          price: 300,
          sales: 800,
          prove: '/static/images/cleaning2.png'
        },
        'KF174194004243588': {
          id: 'KF174194004243588',
          gname: '除螨服务',
          price: 300,
          sales: 600,
          prove: '/static/images/cleaning3.png'
        }
      };

      console.log('查找商品ID:', orderData.gid);
      const currentGoodsInfo = goodsInfo[orderData.gid];
      
      if (!currentGoodsInfo) {
        console.error('未找到商品信息，商品ID:', orderData.gid);
        wx.showToast({
          title: '商品信息不存在',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
        return;
      }

      const totalPrice = currentGoodsInfo.price;
      const finalPrice = totalPrice - this.data.discount;

      this.setData({
        orderData: orderData,
        goodsInfo: currentGoodsInfo,
        totalPrice: totalPrice,
        finalPrice: finalPrice,
        discountPrice: this.data.discount,
        orderInfo: currentGoodsInfo
      });
    }
  },

  // 提交订单
  submitOrder: function() {
    // 防重复提交
    if (this.data.isSubmitting) {
      return;
    }

    this.setData({
      isSubmitting: true
    });

    // 准备订单数据
    const orderData = {
      oid: this.data.currentOid,
      nid: 1107,
      gid: this.data.orderData.gid,
      sid: Math.floor(Math.random() * 10) + 1,
      address: this.data.orderData.address || '河北省保定市万博广场',
      phone: '15630352072',
      date: this.data.orderData.appointmentTime,
      duration: this.data.orderData.duration || 2,
      status: 0,
      price: this.data.finalPrice
    };

    console.log('提交订单数据:', orderData);

    wx.request({
      url: 'http://localhost:9205/order/add',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: orderData,
      success: (res) => {
        console.log('创建订单响应:', res);
        
        // 只要状态码是200就认为成功，因为后端添加成功时返回空数据
        if (res.statusCode === 200) {
          // 订单创建成功
          this.setData({
            currentOid: this.data.currentOid + 1,
            isSubmitting: false
          });
          
          console.log('订单创建成功，订单ID:', orderData.oid);
          
          // 跳转到支付页面
          wx.redirectTo({
            url: '/pages/order/payment/index?orderId=' + orderData.oid + '&amount=' + this.data.finalPrice,
            success: (res) => {
              console.log('跳转成功:', res);
            },
            fail: (err) => {
              console.error('跳转失败:', err);
              wx.showToast({
                title: '页面跳转失败',
                icon: 'none'
              });
            }
          });
        } else {
          console.error('创建订单失败，响应状态码:', res.statusCode);
          this.setData({
            isSubmitting: false
          });
          wx.showToast({
            title: '创建订单失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('创建订单请求失败:', err);
        this.setData({
          isSubmitting: false
        });
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  },

  // 调用支付
  requestPayment: function(orderId) {
    wx.request({
      url: 'http://localhost:9205/api/pay/create',
      method: 'POST',
      data: {
        orderId: orderId,
        amount: this.data.discountPrice,
        description: this.data.orderInfo.gname
      },
      success: (res) => {
        // 调用微信支付
        wx.requestPayment({
          timeStamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.package,
          signType: res.data.signType,
          paySign: res.data.paySign,
          success: (res) => {
            wx.showToast({
              title: '支付成功',
              icon: 'success'
            });
            // 跳转到支付成功页面
            wx.redirectTo({
              url: '/pages/services/homecare/payment-success/index?orderId=' + orderId
            });
          },
          fail: (err) => {
            wx.showToast({
              title: '支付失败',
              icon: 'none'
            });
          }
        });
      },
      fail: (err) => {
        wx.showToast({
          title: '创建支付订单失败',
          icon: 'none'
        });
      }
    });
  },

  // 确认支付按钮点击事件
  confirmPayment: function() {
    // 生成订单ID
    const orderId = 'ORDER_' + Date.now();
    // 调用支付
    this.requestPayment(orderId);
  }
}); 